import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_plugin_record/index.dart';
import 'package:just_audio/just_audio.dart';
import 'package:permission_handler/permission_handler.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FlutterPluginRecord record = FlutterPluginRecord();
  bool init = false;
  List<String> paths = [];
  Timer? timer;
  AudioPlayer audioPlayer = AudioPlayer();
  DateTime? lastTime;

  @override
  void initState() {
    super.initState();
    record.responseFromInit.listen((data) {
      setState(() {
        init = data;
      });
    });
    record.responseFromAmplitude.listen((event) {
      if (event.success == true) {
        var e = event.amplitude;
        if (e == null) {
          lastTime ??= DateTime.now();
          DateTime time = DateTime.now();
          Duration duration = time.difference(lastTime!);
          if (duration.inSeconds >= 30) {
            print('超过30秒静音了');
            lastTime = time;
          }
        }
      }
    });
    record.response.listen((event) {
      switch (event.msg) {
        case 'onStop':
          if (event.success == true) {
            setState(() {
              String path = event.path ?? '';
              paths.add('$path duration=${event.audioTimeLength?.toString()}');
            });
          }
          break;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('appbarTitle'),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          if (!init)
            ElevatedButton(onPressed: initRecord, child: Text('初始化录音')),
          if (init) ElevatedButton(onPressed: startRecord, child: Text('开始录音')),
          if (init) ElevatedButton(onPressed: stopRecord, child: Text('停止录音')),
          Expanded(
            child: ListView.builder(
              itemBuilder: (context, index) => Text(paths[index]),
              itemCount: paths.length,
            ),
          )
        ],
      ),
    );
  }

  Future<void> initRecord() async {
    if (!await Permission.microphone.request().isGranted) {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('授予麦克风权限')));
      return;
    }
    record.init();
  }

  Future<void> startRecord() async {
    if (!await Permission.microphone.request().isGranted) {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('授予麦克风权限')));
      return;
    }
    record.start();
    timer = Timer(const Duration(seconds: 30), () {
      record.stop();
      startRecord();
    });
  }

  void stopRecord() {
    record.stop();
    if (timer?.isActive ?? false) timer?.cancel();
  }
}
